//
//  DzNetHttp.m
#import "DzNetHttp.h"
@interface DzNetHttp()
@property (strong, nonatomic) AFHTTPSessionManager *manager;
@end
@implementation DzNetHttp
static DzNetHttp *defaultManager = nil;
 + (DzNetHttp*)defaultRequest{
     static dispatch_once_t token;
     dispatch_once(&token, ^{
         if(defaultManager == nil){
             defaultManager = [[DzNetHttp alloc] init];
         }
     });
     return defaultManager;
}
//网络类初始化
- (instancetype)init{
  if(self = [super init]){
      self.manager = [AFHTTPSessionManager manager];
      self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
      self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      self.manager.requestSerializer.timeoutInterval = 10.0;
  }
  return self;
}
//Get请求
- (void)get:(NSString *)apiUrl param:(NSDictionary * __nullable)paramDic success:(HttpRequestSucBlock)successBlack fail:(HttpRequestFailBlock)failBlack{
    [self.manager GET:apiUrl parameters:paramDic headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(responseObject){
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if ([jsonDict[@"code"] integerValue] == 200) {
                successBlack(jsonDict);
            }else {
                [DzAlertHelper showMessage:jsonDict[@"msg"]];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlack(error);
    }];
}
- (void)post:(NSString *)apiUrl param:(NSDictionary * __nullable)paramDic success:(HttpRequestSucBlock)successBlack fail:(HttpRequestFailBlock)failBlack{
    [self.manager POST:apiUrl parameters:paramDic headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(responseObject){
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if([jsonDict[@"code"] intValue] == 200){
                successBlack(jsonDict);
            }else{
                [DzAlertHelper showMessage:jsonDict[@"msg"]];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlack(error);
    }];
}
@end
